package com.sen.common.jwt;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//继承请求过滤器类
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        try {
            //1、请求是被保护的
            if (isProtectedUrl(request)){

                //过滤掉OPTIONS请求，留下GET POST请求
                if (!request.getMethod().equals("OPTIONS")){
                    //校验请求头有没有token信息,顺便将用户ID加入请求头
                    request = JwtUtil.validateTokenAndUserIdHeader(request);
                }
            }
        }catch (Exception e){
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,e.getMessage());
            return;
        }
        //放行
        filterChain.doFilter(request,response);
    }

    //判断请求是否被保护
    private boolean isProtectedUrl(HttpServletRequest request) {
        List<String> protectedPaths = new ArrayList<>();

        //获得用户信息的
        protectedPaths.add("/ums/user/info");
        //帖子的增删改
        protectedPaths.add("/post/create");
        protectedPaths.add("/post/update");
        protectedPaths.add("/post/delete/*");
        //发表评论
        protectedPaths.add("/comment/add_comment");
        //关注与取关
        protectedPaths.add("/relationship/subscribe/*");
        protectedPaths.add("/relationship/unsubscribe/*");
        protectedPaths.add("/relationship/validate/*");
        boolean bFind = false;
        for (String protectedPath : protectedPaths) {
            bFind = pathMatcher.match(protectedPath,request.getServletPath());
            if (bFind){
                break;
            }
        }
        return bFind;
    }

    //必须被spring管理不然jwtFilter不生效
    @Bean
    public FilterRegistrationBean jwtFilter() {
        final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        registrationBean.setFilter(filter);
        return registrationBean;
    }

}
